//
//  ClientViewModel.m
//  Jyxt
//
//  Created by 刘日 on 17/5/25.
//  Copyright © 2017年 DaLian Rental Housing Management. All rights reserved.
//

#import "ClientViewModel.h"
#import "DatabaseTool.h"
#import "NetTool.h"

#define SIGN @"sign"
#define CTOKEN @"cToken"


@implementation ClientViewModel

+ (NSString *)getClientSign{
    NSString *sign = [DatabaseTool getWithKey: SIGN];
    if (!sign) {
        sign = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        [DatabaseTool putWithKey: SIGN value: sign];
    }
    return sign;
}

+ (void)getCTokenWithSuccess: (void (^)(NSString *ctoken))success failed: (void (^)(NSString *reason))failed{
    NSString *cToken = [DatabaseTool getWithKey: CTOKEN];
    if (cToken) {
        success(cToken);
        return;
    }
    [NetTool postWithUrl: APIURL(API_CLIENT_REGISTER) data: @{@"sign" : [self getClientSign]} onSuccess:^(NSDictionary *response) {
        if ([response[@"success"] boolValue]){
            NSString *cToken = response[@"ctoken"];
            [DatabaseTool putWithKey: CTOKEN value: cToken];
            success(cToken);
        }
        else
            failed(@"服务器内部错误");
    } onError:^(NSError *error) {
        failed(@"无法连接到服务器");
    }];
}

+ (void)clearLocalCToken{
    [DatabaseTool removeWithKey: CTOKEN];
}

@end
